import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Task } from '../../entities/task.entity';
import { Project } from '../../entities/project.entity';
import { User } from '../../entities/user.entity';
import { TaskStatus, Priority } from '../../types/enums';
import { TaskTag } from '../../entities/task-tag.entity';
import { TaskComment } from '../../entities/task-comment.entity';
import { Between, Not } from 'typeorm';

@Injectable()
export class TaskService {
  constructor(
    @InjectRepository(Task)
    private taskRepository: Repository<Task>,
    @InjectRepository(Project)
    private projectRepository: Repository<Project>,
    @InjectRepository(User)
    private userRepository: Repository<User>,
    @InjectRepository(TaskTag)
    private taskTagRepository: Repository<TaskTag>,
    @InjectRepository(TaskComment)
    private taskCommentRepository: Repository<TaskComment>,
  ) {}

  /**
   * 创建任务
   */
  async createTask(
    title: string,
    description: string,
    projectId: string,
    startDate: Date,
    dueDate: Date,
    createdById: string,
    status: TaskStatus = TaskStatus.TODO,
    priority: Priority = Priority.MEDIUM,
    assigneeId?: string,
  ): Promise<Task> {
    // 验证日期
    if (startDate >= dueDate) {
      throw new BadRequestException('开始日期必须早于截止日期');
    }

    // 验证项目是否存在
    const project = await this.projectRepository.findOne({ 
      where: { id: projectId } 
    });
    
    if (!project) {
      throw new NotFoundException('项目不存在');
    }
    
    // 验证创建人用户是否存在
    const creator = await this.userRepository.findOne({ 
      where: { id: createdById } 
    });
    
    if (!creator) {
      throw new NotFoundException('创建者不存在');
    }

    // 验证指派人（如果有）
    if (assigneeId) {
      const assignee = await this.userRepository.findOne({ 
        where: { id: assigneeId } 
      });
      
      if (!assignee) {
        throw new NotFoundException('指派的用户不存在');
      }
    }

    // 创建新任务
    const task = this.taskRepository.create({
      title,
      description,
      projectId,
      startDate,
      dueDate,
      status,
      priority,
      assigneeId: assigneeId || '',
      createdById,
    });

    return this.taskRepository.save(task);
  }

  /**
   * 获取项目任务列表
   */
  async getTasksByProject(
    projectId: string, 
    status?: TaskStatus,
    priority?: Priority,
    assigneeId?: string
  ): Promise<Task[]> {
    // 验证项目是否存在
    await this.findProjectById(projectId);
    
    // 构建查询
    const queryBuilder = this.taskRepository.createQueryBuilder('task')
      .leftJoinAndSelect('task.assignee', 'assignee')
      .leftJoinAndSelect('task.createdBy', 'createdBy')
      .where('task.projectId = :projectId', { projectId })
      .orderBy('task.createdAt', 'DESC');
    
    // 应用过滤条件
    if (status) {
      queryBuilder.andWhere('task.status = :status', { status });
    }
    
    if (priority) {
      queryBuilder.andWhere('task.priority = :priority', { priority });
    }
    
    if (assigneeId) {
      queryBuilder.andWhere('task.assigneeId = :assigneeId', { assigneeId });
    }
    
    return queryBuilder.getMany();
  }

  /**
   * 获取所有任务
   */
  async getAllTasks(
    status?: TaskStatus,
    priority?: Priority,
    assigneeId?: string
  ): Promise<Task[]> {
    // 构建查询
    const queryBuilder = this.taskRepository.createQueryBuilder('task')
      .leftJoinAndSelect('task.project', 'project')
      .leftJoinAndSelect('task.assignee', 'assignee')
      .leftJoinAndSelect('task.createdBy', 'createdBy')
      .orderBy('task.createdAt', 'DESC');
    
    // 应用过滤条件
    if (status) {
      queryBuilder.andWhere('task.status = :status', { status });
    }
    
    if (priority) {
      queryBuilder.andWhere('task.priority = :priority', { priority });
    }
    
    if (assigneeId) {
      queryBuilder.andWhere('task.assigneeId = :assigneeId', { assigneeId });
    }
    
    return queryBuilder.getMany();
  }

  /**
   * 获取任务详情
   */
  async getTaskById(id: string): Promise<Task> {
    const task = await this.taskRepository.findOne({ 
      where: { id },
      relations: ['assignee', 'createdBy', 'project']
    });
    
    if (!task) {
      throw new NotFoundException('任务不存在');
    }
    
    return task;
  }

  /**
   * 更新任务
   */
  async updateTask(
    id: string,
    title?: string,
    description?: string,
    status?: TaskStatus,
    priority?: Priority,
    assigneeId?: string,
    startDate?: Date,
    dueDate?: Date,
  ): Promise<Task> {
    const task = await this.getTaskById(id);
    
    // 更新字段
    if (title !== undefined) task.title = title;
    if (description !== undefined) task.description = description;
    if (status !== undefined) task.status = status;
    if (priority !== undefined) task.priority = priority;
    
    // 处理日期更新
    const newStartDate = startDate || task.startDate;
    const newDueDate = dueDate || task.dueDate;
    
    // 验证日期
    if (newStartDate >= newDueDate) {
      throw new BadRequestException('开始日期必须早于截止日期');
    }
    
    task.startDate = newStartDate;
    task.dueDate = newDueDate;
    
    // 处理指派人更新
    if (assigneeId !== undefined) {
      if (assigneeId) {
        // 验证用户是否存在
        const assignee = await this.userRepository.findOne({ 
          where: { id: assigneeId } 
        });
        
        if (!assignee) {
          throw new NotFoundException('指派的用户不存在');
        }
        task.assigneeId = assigneeId;
      } else {
        // 如果为null或空字符串，使用空字符串
        task.assigneeId = '';
      }
    }
    
    return this.taskRepository.save(task);
  }

  /**
   * 删除任务（软删除）
   */
  async deleteTask(id: string): Promise<{ message: string }> {
    const task = await this.getTaskById(id);
    
    await this.taskRepository.softDelete(id);
    
    return { message: '任务已删除' };
  }

  /**
   * 永久删除任务
   */
  async permanentDeleteTask(id: string): Promise<void> {
    const task = await this.getTaskById(id);

    // 如果任务未被软删除，不允许永久删除
    if (!task.deletedAt) {
      throw new BadRequestException('只能永久删除已经被软删除的任务');
    }

    // 删除任务的标签关联
    await this.taskTagRepository.delete({ taskId: id });
    
    // 删除任务的评论
    if (this.taskCommentRepository) {
      await this.taskCommentRepository.delete({ taskId: id });
    }

    // 永久删除任务
    await this.taskRepository.remove(task);
  }
  
  /**
   * 更新任务状态
   */
  async updateTaskStatus(id: string, status: TaskStatus): Promise<Task> {
    const task = await this.getTaskById(id);
    
    task.status = status;
    
    return this.taskRepository.save(task);
  }
  
  /**
   * 查询项目（内部方法）
   */
  private async findProjectById(id: string): Promise<Project> {
    const project = await this.projectRepository.findOne({ 
      where: { id } 
    });
    
    if (!project) {
      throw new NotFoundException('项目不存在');
    }
    
    return project;
  }

  /**
   * 根据截止日期范围查找任务
   * @param startDate 开始日期
   * @param endDate 结束日期
   * @returns 在日期范围内的任务列表
   */
  async findTasksByDueDate(startDate: Date, endDate: Date): Promise<Task[]> {
    return this.taskRepository.find({
      where: {
        dueDate: Between(startDate, endDate),
        status: Not(TaskStatus.DONE), // 排除已完成的任务
      },
      relations: ['assignee', 'createdBy']
    });
  }
} 